<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // let p2 = newe Promise((resolve,reject)=>{});
      // console.log(p2);

      // 自定义MyPromise类
      class Mypromise {
        constructor(handle) {
          //handle --->(resolve,reject)=>{}
          // 状态；
          //   console.log(this); //不要关注this的定义，需要关注this的调用
          this["[[PromiseState]]"] = "pendding";
          this["[[PromiseResult]]"] = undefined;
          //   handle(
          //     function (val) {
          // 外部的resolve函数
          //       //   console.log(this);   // 不用bind是undefined，使用则是p实例
          //       this["[[PromiseState]]"] = "fulfilled";
          //       this["[[PromiseResult]]"] = val;
          //     }.bind(this),
          //     function (val) {
          // 外部的reject函数
          //       //   console.log(this);
          //       this["[[PromiseState]]"] = "reject";
          //       this["[[PromiseResult]]"] = val;
          //     }.bind(this)
          //   );

          handle(this.#_resolve.bind(this), this.#_reject.bind(this));
        }

        #_resolve(val) {
          //私有方法 需要在前面加上#号，只能类的内部调用外部不能调用
          // 外部的resolve函数
          // console.log(this);
          this["[[PromiseState]]"] = "fulfilled";
          this["[[PromiseResult]]"] = val;
        }

        #_reject(err) {
          this["[[PromiseState]]"] = "rejected"; //改变状态
          this["[[PromiseResult]]"] = err; // 改变结果值
          setTimeout(() => {
            throw new Error(err); //抛出错误
          });
        }
      }

      let p = new Mypromise((resolve, reject) => {
        // resolve("success");
        // reject("error");
      });
      console.log(p);
      //   p.#_resolve();

      let p3 = new Mypromise((resolve, reject) => {});
      console.log(p);
      let p4 = new Mypromise((resolve, reject) => {});
      console.log(p);
    </script>
  </body>
</html>
